import tensorflow as tf

mnist = tf.keras.datasets.mnist

# 加载官方提供的数据
# 手写数字数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# 构建机器学习模型
model = tf.keras.models.Sequential([
    # 输入层
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    # 隐藏层
    tf.keras.layers.Dense(128, activation='relu'),
    # 防止过拟合，随机删除参数
    tf.keras.layers.Dropout(0.2),
    # 输出层，10个类别
    tf.keras.layers.Dense(10)
])

# 损失函数
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)

# 编译模型
model.compile(optimizer='adam',
              loss=loss_fn,
              metrics=['accuracy'])

# 训练模型
model.fit(x_train, y_train, epochs=5)

# 模型评估
model.evaluate(x_test, y_test, verbose=2)
